package comm;

import java.net.*;
import java.io.*;

public class Communicator {

	static final String IP = "127.0.0.1";
	static final int PORT = 9527;

	private Socket socket;
	BufferedWriter os;
	DataInputStream is;

	public Communicator() throws IOException {
		socket = new Socket(IP, PORT);
		os = new BufferedWriter(
				new OutputStreamWriter(socket.getOutputStream()));
		is = new DataInputStream(socket.getInputStream());
	}

	public void sendMsg(Message m) throws IOException {
		os.write(m.msg);
		os.flush();
		if (client.Main.debug) {
			System.out.println(client.Main.name + " send " + m.getMsgType());
		}
	}

	public void sendChessInfo(ChessInfo c) throws IOException {
		os.write(c.index);
		os.write(c.color);
		os.write(c.row);
		os.write(c.col);
		for (int i = 0; i < 4; i++)
			os.write(c.reserved[i]);
		os.flush();
		if (client.Main.debug) {
			System.out.println(client.Main.name + " send chess_info: ");
			c.print();
		}
	}

	public Message recMsg() throws IOException {
		Message m = new Message(is.readByte());
		if (client.Main.debug) {
			System.out.println(client.Main.name + " receive " + m.getMsgType());
		}
		return m;
	}

	public RejectInfo recRejectInfo() throws IOException {
		RejectInfo ri;
		byte r = is.readByte();
		byte s = is.readByte();
		byte p = is.readByte();
		byte rs = is.readByte();
		ri = new RejectInfo(r, s, p, rs);
		if (client.Main.debug) {
			System.out.println(client.Main.name + " receive rej_info");
		}
		return ri;
	}

	public ChessInfo recChessInfo() throws IOException {
		ChessInfo ci;
		byte i = is.readByte();
		byte clr = is.readByte();
		byte r = is.readByte();
		byte c = is.readByte();
		byte[] rs = new byte[4];
		is.read(rs);
		ci = new ChessInfo(i, clr, r, c, rs);
		if (client.Main.debug) {
			System.out.println(client.Main.name + " receive chess_info");
		}
		return ci;
	}

}
